package com.powerbank.user.controller;

import com.powerbank.common.result.Result;
import com.powerbank.common.utils.JwtUtils;
import com.powerbank.user.service.CouponService;
import com.powerbank.user.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.NotBlank;
import java.math.BigDecimal;
import java.util.List;

/**
 * 优惠券控制器
 */
@Slf4j
@RestController
@RequestMapping("/coupon")
public class CouponController {

    @Autowired
    private CouponService couponService;

    @Autowired
    private JwtUtils jwtUtils;

    /**
     * 获取用户可用优惠券列表
     */
    @GetMapping("/available")
    public Result<List<UserCouponVO>> getAvailableCoupons(@RequestParam(required = false, defaultValue = "ALL") String applyScope,
                                                          @RequestParam BigDecimal amount,
                                                          HttpServletRequest request) {
        Long userId = getUserIdFromToken(request);
        
        try {
            List<UserCouponVO> coupons = couponService.getAvailableCoupons(userId, applyScope, amount);
            return Result.success("可用优惠券查询成功", coupons);
        } catch (Exception e) {
            log.error("查询可用优惠券失败：{}", e.getMessage(), e);
            return Result.error("查询可用优惠券失败：" + e.getMessage());
        }
    }

    /**
     * 获取用户所有优惠券（分页）
     */
    @GetMapping("/list")
    public Result<PageResult<UserCouponVO>> getUserCoupons(@RequestParam(required = false) Integer status,
                                                           @RequestParam(defaultValue = "1") int page,
                                                           @RequestParam(defaultValue = "10") int size,
                                                           HttpServletRequest request) {
        Long userId = getUserIdFromToken(request);
        
        try {
            PageResult<UserCouponVO> result = couponService.getUserCoupons(userId, status, page, size);
            return Result.success("优惠券列表查询成功", result);
        } catch (Exception e) {
            log.error("查询优惠券列表失败：{}", e.getMessage(), e);
            return Result.error("查询优惠券列表失败：" + e.getMessage());
        }
    }

    /**
     * 领取优惠券
     */
    @PostMapping("/receive/{templateId}")
    public Result<Void> receiveCoupon(@PathVariable @NotNull(message = "模板ID不能为空") Long templateId,
                                      HttpServletRequest request) {
        Long userId = getUserIdFromToken(request);
        
        try {
            boolean success = couponService.receiveCoupon(userId, templateId);
            return success ? Result.success("领取成功", (Void) null) : Result.error("领取失败");
        } catch (Exception e) {
            log.error("领取优惠券失败：{}", e.getMessage(), e);
            return Result.error("领取失败：" + e.getMessage());
        }
    }

    /**
     * 计算优惠金额
     */
    @GetMapping("/calculate-discount/{couponId}")
    public Result<BigDecimal> calculateDiscountAmount(@PathVariable @NotNull(message = "优惠券ID不能为空") Long couponId,
                                                      @RequestParam BigDecimal amount) {
        try {
            BigDecimal discountAmount = couponService.calculateDiscountAmount(couponId, amount);
            return Result.success("优惠金额计算成功", discountAmount);
        } catch (Exception e) {
            log.error("计算优惠金额失败：{}", e.getMessage(), e);
            return Result.error("计算优惠金额失败：" + e.getMessage());
        }
    }

    /**
     * 验证优惠券是否可用
     */
    @PostMapping("/validate/{couponId}")
    public Result<Boolean> validateCoupon(@PathVariable @NotNull(message = "优惠券ID不能为空") Long couponId,
                                          @RequestParam BigDecimal amount,
                                          HttpServletRequest request) {
        Long userId = getUserIdFromToken(request);
        
        try {
            boolean valid = couponService.validateCoupon(userId, couponId, amount);
            return Result.success("优惠券验证完成", valid);
        } catch (Exception e) {
            log.error("验证优惠券失败：{}", e.getMessage(), e);
            return Result.error("验证优惠券失败：" + e.getMessage());
        }
    }

    /**
     * 获取可领取的优惠券模板列表
     */
    @GetMapping("/templates")
    public Result<List<CouponTemplateVO>> getReceivableTemplates(HttpServletRequest request) {
        Long userId = getUserIdFromToken(request);
        
        try {
            List<CouponTemplateVO> templates = couponService.getReceivableTemplates(userId);
            return Result.success("可领取优惠券模板查询成功", templates);
        } catch (Exception e) {
            log.error("查询可领取优惠券模板失败：{}", e.getMessage(), e);
            return Result.error("查询可领取优惠券模板失败：" + e.getMessage());
        }
    }

    /**
     * 获取用户优惠券统计
     */
    @GetMapping("/summary")
    public Result<CouponSummaryVO> getCouponSummary(HttpServletRequest request) {
        Long userId = getUserIdFromToken(request);
        
        try {
            CouponSummaryVO summary = couponService.getCouponSummary(userId);
            return Result.success("优惠券统计信息获取成功", summary);
        } catch (Exception e) {
            log.error("获取优惠券统计信息失败：{}", e.getMessage(), e);
            return Result.error("获取优惠券统计信息失败：" + e.getMessage());
        }
    }

    /**
     * 自动发放新用户优惠券（内部接口）
     */
    @PostMapping("/issue-new-user/{userId}")
    public Result<Integer> issueNewUserCoupons(@PathVariable @NotNull(message = "用户ID不能为空") Long userId) {
        try {
            int issuedCount = couponService.issueNewUserCoupons(userId);
            return Result.success("新用户优惠券发放成功", issuedCount);
        } catch (Exception e) {
            log.error("发放新用户优惠券失败：{}", e.getMessage(), e);
            return Result.error("发放新用户优惠券失败：" + e.getMessage());
        }
    }

    /**
     * 自动发放生日优惠券（内部接口）
     */
    @PostMapping("/issue-birthday/{userId}")
    public Result<Integer> issueBirthdayCoupons(@PathVariable @NotNull(message = "用户ID不能为空") Long userId) {
        try {
            int issuedCount = couponService.issueBirthdayCoupons(userId);
            return Result.success("生日优惠券发放成功", issuedCount);
        } catch (Exception e) {
            log.error("发放生日优惠券失败：{}", e.getMessage(), e);
            return Result.error("发放生日优惠券失败：" + e.getMessage());
        }
    }

    /**
     * 退还优惠券（内部接口）
     */
    @PostMapping("/refund/{orderId}")
    public Result<Void> refundCoupon(@PathVariable @NotNull(message = "订单ID不能为空") Long orderId) {
        try {
            boolean success = couponService.refundCoupon(orderId);
            return success ? Result.success("优惠券退还成功", (Void) null) : Result.error("优惠券退还失败");
        } catch (Exception e) {
            log.error("退还优惠券失败：{}", e.getMessage(), e);
            return Result.error("退还优惠券失败：" + e.getMessage());
        }
    }

    /**
     * 兑换优惠券
     */
    @PostMapping("/exchange/{couponCode}")
    public Result<Void> exchangeCoupon(@PathVariable @NotBlank(message = "兑换码不能为空") String couponCode,
                                      HttpServletRequest request) {
        Long userId = getUserIdFromToken(request);
        
        try {
            boolean success = couponService.exchangeCoupon(userId, couponCode);
            return success ? Result.success("兑换成功", (Void) null) : Result.error("兑换失败：" + (success ? "" : "兑换码无效或已使用"));
        } catch (Exception e) {
            log.error("兑换优惠券失败：{}", e.getMessage(), e);
            return Result.error("兑换失败：" + e.getMessage());
        }
    }

    /**
     * 从请求中获取用户ID
     */
    private Long getUserIdFromToken(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
            String token = bearerToken.substring(7);
            return jwtUtils.getUserIdFromToken(token);
        }
        throw new RuntimeException("Token不能为空");
    }
}